package org.egedede.osgi.guishell;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.SwingUtilities;

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;

/**
 * Hello world!
 *
 */
public class Activator implements org.osgi.framework.BundleActivator, Runnable {

	private GuiShellFrame frame;
	private BundleContext context;
	private long bundleId;

	public void start(BundleContext context) throws Exception {
		this.context = context;
		bundleId = context.getBundle().getBundleId();
		if (SwingUtilities.isEventDispatchThread()) {
			run();
		} else {
			try {
				javax.swing.SwingUtilities.invokeAndWait(this);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	public void stop(BundleContext arg0) throws Exception {
		// TODO Auto-generated method stub
		frame.dispose();
	}

	public void run() {
		frame = new GuiShellFrame();
		System.out.println("Starting");
		frame.setContext(context);
		System.out.println("context set");
		frame.setVisible(true);
		System.out.println("Visible");
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent evt) {
				try {
					context.getBundle(bundleId).stop();
				} catch (BundleException ex) {
					ex.printStackTrace();
				}
			}
		});
	}

}
